﻿using System.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using OAuthTwitterWrapper.JsonTypes;

namespace OAuthTwitterWrapper
{
	public class OAuthTwitterWrapper 
    {
		public IAuthenticateSettings AuthenticateSettings { get; set; }
		public ITimeLineSettings TimeLineSettings { get; set; }
		public ISearchSettings SearchSettings { get; set; }


		/// <summary>
		/// This allows the authentications settings to be passed in
		/// </summary>
		/// <param name="authenticateSettings"></param>
		public OAuthTwitterWrapper(IAuthenticateSettings authenticateSettings)
		{
			AuthenticateSettings = authenticateSettings;
		}

        public HttpArgument Get(string urlFormat, params string[] args)
        {
            string url = string.Format(urlFormat, args);
            var searchJson = string.Empty;
            IAuthenticate authenticate = new Authenticate();
            AuthResponse twitAuthResponse = authenticate.AuthenticateMe(AuthenticateSettings);

            var result = DownloadUrl(url, twitAuthResponse.TokenType, twitAuthResponse.AccessToken);
            result.UrlFormat = urlFormat;
            result.Json = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Result);
            return result;
        }
        public HttpArgument DownloadUrl(string apiUrl, string tokenType, string accessToken)
        {
            var json = string.Empty;
            WebClient client = new WebClient();
            var timelineHeaderFormat = "{0} {1}";
            client.Headers.Add("Authorization",
                                        string.Format(timelineHeaderFormat, tokenType,
                                                      accessToken));
            json = client.DownloadString(apiUrl);
            return new HttpArgument() { Result = json, Url = apiUrl };
        }
    }
    public class HttpArgument
    {
        public string UrlFormat { get; set; }
        public string Url { get; set; }
        public string Result { get; set; }
        public dynamic Json { get; set; }
    }
}
